import sys, os, time, shutil, hashlib
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QLineEdit
import mwdesign as cui

Objective = cui.Ui_MainWindow

class MainWindow(QtWidgets.QMainWindow,Objective):
    def __init__(self,parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.open_dir)
        self.commandLinkButton_2.clicked.connect(QtCore.QCoreApplication.instance().quit)
        self.checkBox_2.clicked.connect(self.carousel_use)
        self.pushButton_2.clicked.connect(self.cover_img_set)
        self.pushButton_3.clicked.connect(self.carousel_img_set)
        self.pushButton_4.clicked.connect(self.show_pwd)
        self.commandLinkButton.clicked.connect(self.md_process)
        self.img_filter = '网络可用图像格式(*.bmp , *.jpeg , *.jpg , *.png , *.svg , *.tif , *.gif);;' \
                          'JPEG图像(*.jpeg , *.jpg);;' \
                          'PNG图像(*.png);;' \
                          'BMP位图格式(*.bmp);;' \
                          'SVG矢量网络图像格式(*.svg);;' \
                          'TIFF标签图像格式(*.tif);;' \
                          'GIF动图格式(*.gif)'

    def carousel_use(self):
        if self.checkBox_2.isChecked():
            self.lineEdit_4.setEnabled(True)
            self.pushButton_3.setEnabled(True)
        else:
            self.lineEdit_4.setEnabled(False)
            self.pushButton_3.setEnabled(False)

    def carousel_img_set(self):
        self.lineEdit_4.clear()
        temp = self.get_img_dir()
        self.lineEdit_4.insert(temp[0])

    def cover_img_set(self):
        self.lineEdit_3.clear()
        temp = self.get_img_dir()
        self.lineEdit_3.insert(temp[0])

    def get_img_dir(self):
        global md_Dir
        open_img_dir = QFileDialog.getOpenFileName(self,'选择图像文件',md_Dir,self.img_filter)
        return open_img_dir

    def show_pwd(self):
        if self.lineEdit_5.echoMode() == QLineEdit.Password:
            self.lineEdit_5.setEchoMode(QLineEdit.Normal)
        else:
            self.lineEdit_5.setEchoMode(QLineEdit.Password)

    def open_dir(self):
        global md_Dir
        md_Dir = None
        open_dir_name = QFileDialog.getExistingDirectory()
        if open_dir_name != "":
            self.lineEdit.insert(open_dir_name)
            self.Check_And_Insert(open_dir_name)

    # 检查导入Markdown文件夹内信息是否符合规范
    def Check_And_Insert(self, instr):
        global md_Text,md_Name,md_Dir
        md_Text = None
        md_Name = None
        list_temp = os.listdir(instr)
        #QMessageBox.information(self,"Test",str(list_temp))
        mdf = None
        oaths = None
        for i in list_temp:
            sub_dir = instr + '/' + i
            if os.path.isfile(sub_dir):
                if i.split('.')[-1] == 'md':
                    mdf = sub_dir
                    md_Name = i.split('.')[-2]
                    break
            else:
                continue
        #QMessageBox.information(self, "错误", mdf)
        if mdf == None:
            QMessageBox.information(self,"错误","文件夹中不包含任何Markdown文件。")
        else:
            try:
                f = open(mdf,'r',encoding="utf-8")
                md_Temp = f.read()
                f.close()
                md_Dir = instr
                self.clean_statue()
                self.enable_actor()
                #QMessageBox.information(self,'Test',md_Text)
                QMessageBox.information(self, '信息', "已成功导入原Markdown信息。")
                if len(md_Temp.split("---\n")) > 2:
                    info_s = md_Temp.split("---\n")[1]
                    #QMessageBox.information(self,'Test',info_s)
                    if info_s[-2:]== '--':
                        md_Text = md_Temp
                    else:
                        info_s = info_s.split('\n')
                        #QMessageBox.information(self, 'Test', str(info_s))
                        self.list_insert(info_s)
                        md_Text = md_Temp.split("---\n")[2]
                        #QMessageBox.information(self, '信息', "已成功导入原Markdown信息。")
                else:
                    md_Text = md_Temp
            except Exception as sd:
                QMessageBox.information(self, 'Error', "Markdown打开错误！\n"+str(sd))

    # 读取Markdown信息块信息
    def list_insert(self,inlist):
        #print(inlist)
        for i in inlist:
            zuo = i.split(": ")
            you = i.split(" - ")
            if zuo[0] == 'title':
                self.lineEdit_2.insert(zuo[1])
            elif zuo[0] == 'author':
                self.comboBox.setEditText(zuo[1])
            elif zuo[0] == 'top':
                if zuo[1] == "true":
                    self.checkBox.setChecked(True)
                else:
                    self.checkBox.setChecked(False)
            elif zuo[0] == 'cover':
                if zuo[1] == "true":
                    self.checkBox_2.setChecked(True)
                    self.lineEdit_4.setEnabled(True)
                    self.pushButton_3.setEnabled(True)
                else:
                    self.checkBox_2.setChecked(False)
                    self.lineEdit_4.setEnabled(False)
                    self.pushButton_3.setEnabled(False)
            elif zuo[0] == 'toc':
                if zuo[1] == "true":
                    self.checkBox_3.setChecked(True)
                else:
                    self.checkBox_3.setChecked(False)
            elif zuo[0] == 'mathjax':
                if zuo[1] == "true":
                    self.checkBox_4.setChecked(True)
                else:
                    self.checkBox_4.setChecked(False)
            elif zuo[0] == 'summary':
                self.textEdit.setText(zuo[1])
            elif zuo[0] == 'categories':
                self.comboBox_2.setEditText(zuo[1])
            #elif you[1] != '':
                #self.lineEdit_7.insert(you[1]+';')
            #print(zuo)
            if len(you)>1:
                self.lineEdit_7.insert(you[1]+' ')

    # 清除对象状态
    def clean_statue(self):
        self.lineEdit_2.clear()
        self.comboBox.setCurrentIndex(-1)
        self.lineEdit_3.clear()
        self.checkBox.setChecked(False)
        self.checkBox_2.setChecked(False)
        self.lineEdit_4.setEnabled(False)
        self.lineEdit_4.clear()
        self.lineEdit_5.clear()
        self.checkBox_3.setChecked(False)
        self.checkBox_4.setChecked(False)
        self.comboBox.setCurrentIndex(-1)
        self.lineEdit_7.clear()
        self.textEdit.clear()

    # 对象可使用使能打开
    def enable_actor(self):
        self.lineEdit_2.setEnabled(True)
        self.comboBox.setEnabled(True)
        self.lineEdit_3.setEnabled(True)
        self.pushButton_2.setEnabled(True)
        self.checkBox.setEnabled(True)
        self.checkBox_2.setEnabled(True)
        self.lineEdit_5.setEnabled(True)
        self.pushButton_4.setEnabled(True)
        self.checkBox_3.setEnabled(True)
        self.checkBox_4.setEnabled(True)
        self.comboBox_2.setEnabled(True)
        self.lineEdit_7.setEnabled(True)
        self.textEdit.setEnabled(True)
        self.commandLinkButton.setEnabled(True)

    def md_process(self):
        global md_Text, md_Name, md_Dir
        # 信息文件头
        info_m = '---'
        # 新闻标题处理代码
        if self.lineEdit_2.text() == '':
            QMessageBox.information(self,'Error',"请填写新闻标题。")
            return 0
        info_m += '\ntitle: ' + self.lineEdit_2.text()
        #print(1,info_m)
        # 发布时间处理代码
        ti = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        info_m += '\ndate: ' + ti
        #print(2, info_m)
        # 文章发布者处理代码
        if self.comboBox.currentText() == '':
            QMessageBox.information(self, 'Error', "请填写发布者名称。")
            return 0
        info_m += '\nauthor: ' + self.comboBox.currentText()
        #print(3, info_m)
        # 文章封面图片处理代码
        try:
            if self.lineEdit_3.text() == '':
                raise Exception('未输入图像地址')
            copy_dir = md_Dir+'/'+md_Name
            if not os.path.exists(copy_dir):
                os.makedirs(copy_dir)
            if not os.path.exists(copy_dir + '/' + self.lineEdit_3.text().split('/')[-1]):
                shutil.copy(self.lineEdit_3.text(),copy_dir)
            date_dir = '/' + ti.split(' ')[0].replace('-','/') + '/' + md_Name + '/' + \
                       self.lineEdit_3.text().split('/')[-1]
            info_m += '\nimg: ' + date_dir
        except Exception as et:
            QMessageBox.information(self, 'Error', "封面图为必填项，无法进行封面图像归档。\n"+str(et))
            return 0
        #print(4, info_m)
        # 新闻是否置顶处理代码
        if self.checkBox.isChecked():
            info_m += '\ntop: true'
        else:
            info_m += '\ntop: false'
        #print(5, info_m)
        # 轮播图片处理代码
        if self.checkBox_2.isChecked():
            info_m += '\ncover: true'
            try:
                if self.lineEdit_4.text() == '':
                    raise Exception('未输入图像地址')
                copy_dir = md_Dir + '/' + md_Name
                if not os.path.exists(copy_dir):
                    os.makedirs(copy_dir)
                if not os.path.exists(copy_dir + '/' + self.lineEdit_4.text().split('/')[-1]):
                    shutil.copy(self.lineEdit_4.text(), copy_dir)
                date_dir = '/' + ti.split(' ')[0].replace('-', '/') + '/' + md_Name + '/' + \
                           self.lineEdit_4.text().split('/')[-1]
                info_m += '\ncoverImg: ' + date_dir
            except Exception as et:
                info_m += '\ncoverImg: '
        else:
            info_m += '\ncover: false\ncoverImg: '
        #print(6, info_m)
        # 加密密码处理代码
        if self.lineEdit_5.text() == '':
            info_m += '\npassword: '
        else:
            hash_value = hashlib.sha256(self.lineEdit_5.text().encode('utf-8')).hexdigest()
            info_m += '\npassword: ' + hash_value
        #print(7, info_m)
        # 开启TOC处理代码
        if self.checkBox_3.isChecked():
            info_m += '\ntoc: true'
        else:
            info_m += '\ntoc: false'
        # 开启公式处理代码（Mathjax）
        if self.checkBox_4.isChecked():
            info_m += '\nmathjax: true'
        else:
            info_m += '\nmathjax: false'
        #print(8, info_m)
        # 分类设置处理代码
        if self.comboBox_2.currentText() == '':
            QMessageBox.information(self, 'Error', "必须对发布新闻进行分类！")
            return 0
        else:
            info_m += '\ncategories: ' + self.comboBox_2.currentText()
        #print(9, info_m)
        # 新闻摘要处理代码
        if self.textEdit.toPlainText() == '':
            QMessageBox.information(self, 'Error', "必须填写新闻摘要！")
            return 0
        else:
            info_m += '\nsummary: ' + self.textEdit.toPlainText()
        #print(10, info_m)
        # 新闻标签处理代码
        temp = self.lineEdit_7.text().split(' ')
        if temp == ['']:
            QMessageBox.information(self, 'Error', "必须填写新闻标签！")
            return 0
        else:
            info_m += '\ntags: '
            for i in temp:
                if i != '':
                    info_m += '\n  - ' + i
                else:
                    continue
        info_m += '\n---\n'
        # 文件组合
        if md_Text is None:
            QMessageBox.information(self, 'Error', "软件识别文章为空，停止处理。")
            return 0
        temp_all = info_m + md_Text
        #print(temp_all)
        #print(info_m)
        # 文件处理以及备份
        try:
            shutil.copy(md_Dir+'/'+md_Name+'.md',md_Dir+'/'+md_Name+'.md.save')
            f = open(md_Dir+'/'+md_Name+'.md','w',encoding='utf-8')
            f.write(temp_all)
            f.close()
        except Exception as et:
            QMessageBox.information(self,'Error',"文件处理时出错。\n" + str(et))
            return 0
        QMessageBox.information(self, 'Info', "文件处理成功！\n请将目录下的“"+md_Name+'.md”文件与“'+
                                md_Name+'”文件夹在确保没有重名的情况下上传到服务器的“/source/_posts”'
                                        '文件夹中。\n上传完成后使用“hexo d -g”进行发布处理。')
        return 1

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = MainWindow()
    MainWindow.show()
    sys.exit(app.exec_())


